package com.reger.l2cache.autoconfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import com.reger.l2cache.aspect.L2CacheAspect;
import com.reger.l2cache.core.Cache;
import com.reger.l2cache.core.LocalCache;
import com.reger.l2cache.core.RedisCache;
import com.reger.l2cache.listener.annotation.RedisListener;

public class L2CacheAutoConfig {

	private static final Logger log = LoggerFactory.getLogger(L2CacheAutoConfig.class);

	@Autowired(required = false)
	private RedisConnectionFactory connectionFactory;

	@Autowired(required = false)
	private Cache cache;

	@Bean
	public L2CacheAspect l2CacheAspect() {
		if (this.cache == null) {
			RedisCache redisCache = null;
			if (connectionFactory != null) {
				redisCache = new RedisCache(connectionFactory);
			} else {
				log.warn("由于没有初始化RedisConnectionFactory，所以只能初始化默认的一级缓存");
			}
			this.cache = new LocalCache(redisCache);
			log.info("初始化默认的二级缓存方案....");
		}
		return new L2CacheAspect(this.cache);
	}

	@RedisListener(channelPattern = Cache.L2CACHE_SYNC_PUT_CHANNEL)
	public void putListener(String cacheKey) {
		this.syncDel(cacheKey);
	}

	@RedisListener(channelPattern = Cache.L2CACHE_SYNC_DEL_CHANNEL)
	public void delListener(String cacheKey) {
		this.syncDel(cacheKey);
	}

	private void syncDel(String cacheKey) {
		log.debug("收到待同步的数据 {}",cacheKey);
		if (cache != null && cache instanceof LocalCache) {
			((LocalCache) cache).del(cacheKey);
		}
	}
}
